import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:robot3/pojo.dart';
import 'package:robot3/services.dart';
import 'package:robot3/viewmodel/CustomerDetailsProvider.dart';
import 'package:robot3/widgets.dart';
import 'package:intl/intl.dart';

import 'Robot.dart';
import 'backButton1.dart';

const fromAndroid = true;

const platformMethodChannel = MethodChannel(
  'com.abc.robot01.flutter.CustomerRenderDetails',
);

//  商品库详情
void main() {
  runApp(MaterialApp(home: const CustomerRenderDetails()));
}

class CustomerRenderDetails extends StatefulWidget {
  const CustomerRenderDetails({super.key});

  @override
  _CustomerRenderDetailsState createState() => _CustomerRenderDetailsState();
}

class _CustomerRenderDetailsState extends State<CustomerRenderDetails> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CustomerDetailsProvider(),
      child: _ShangpinkuScreen(title: 'Flutter Demo Home Page'),
    );
  }
}

class _ShangpinkuScreen extends StatefulWidget {
  const _ShangpinkuScreen({super.key, required this.title});

  final String title;

  @override
  State<_ShangpinkuScreen> createState() => _PageState();
}

class _PageState extends State<_ShangpinkuScreen> {
  Future<void> _getParams() async {
    try {
      final String result = await platformMethodChannel.invokeMethod('getId');
      print("result:" + result);
      final params = result.split('_');
      print(params[0]);
      print(params[1]);
      final accessToken = params[0];
      print("accessToken:" + accessToken);
      final userId = params[1];
      print("userId:" + userId);
      final companyId = params[2];
      print("companyId:" + companyId);
      final name = params[3];
      final phone = params[4];
      final total = double.parse(params[5]);

      final provider = Provider.of<CustomerDetailsProvider>(
        context,
        listen: false,
      );
      provider
          .getCustomerDetails(
            accessToken,
            userId,
            companyId,
            name,
            phone,
            total,
          )
          .then((value) {});
    } on PlatformException catch (e) {
      print("Failed to get parameters: '${e.message}'.");
    }
  }

  @override
  void initState() {
    super.initState();
    if (fromAndroid) {
      _getParams();
    } else {
      print("initState 0");
      _delayExecution(); // 调用延迟方法
      print("initState 1");
    }
  }

  Future<void> _delayExecution() async {
    await Future.delayed(Duration(seconds: 0), () {
      final provider = Provider.of<CustomerDetailsProvider>(
        context,
        listen: false,
      );
      final args =
          ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>;
      final name = args['name'];
      final phone = args['phone'];
      final total = args['total'];
      provider
          .getCustomerDetails(
            Robot.accessToken,
            Robot.userId,
            Robot.companyId,
            name,
            phone,
            total,
          )
          .then((value) {});
      print("Executed after 1 seconds");
      return;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // Image equivalent to the Image composable
          Image.asset(
            'images/bg.png', // 替换为你的图片路径
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 260 / ratio,
              right: 260 / ratio,
              top: 30 / ratio,
            ),
            child: // 加载完成后显示商品信息
                Content01(child: Content()),
          ),
          Positioned(
            left: 30 / ratio,
            bottom: 30 / ratio,
            child: BackButton1(
              onClick: (text) {
                SystemNavigator.pop();
                // Navigator.of(context).pop();
              },
            ),
          ),
        ],
      ),
    );
  }
}

class Content01 extends StatelessWidget {
  final Widget child;

  const Content01({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TitleText(text: '客户管理详情'),
        SizedBox(height: 10 / ratio),
        Expanded(child: child),
      ],
    );
  }
}

///客户信息
class Info extends StatelessWidget {
  const Info({super.key});

  @override
  Widget build(BuildContext context) {
    final customerInfo = Provider.of<CustomerDetailsProvider>(context);
    return Padding(
      padding: EdgeInsets.only(top: 30 / ratio, bottom: 19 / ratio),
      child: Row(
        children: [
          SizedBox(
            width: 58,
            child: Text(
              overflow: TextOverflow.ellipsis,
              customerInfo.customerName,
              style: TextStyle(
                fontSize: 24 / ratio,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),

          SizedBox(width: 10 / ratio),
          SizedBox(
            width: 50,
            child: Text(
              customerInfo.phoneNumber,
              style: TextStyle(
                fontSize: 24 / ratio,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),

          SizedBox(width: 24 / ratio),
          Text(
            "目标客户",
            style: TextStyle(fontSize: 24 / ratio, fontWeight: FontWeight.bold),
          ),
          SizedBox(width: 100 / ratio),

          SizedBox(
            width: 330 / ratio,
            child: Text(
              "渲染总次数：${customerInfo.renderCount}",
              style: TextStyle(fontSize: 24 / ratio),
            ),
          ),

          Text(
            "渲染总金额：${customerInfo.totalAmount}",
            style: TextStyle(fontSize: 24 / ratio),
          ),
        ],
      ),
    );
  }
}

///Title
class Title extends StatelessWidget {
  const Title({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: MyBlack.withOpacity(0.05),
      child: Padding(
        padding: EdgeInsets.only(
          top: 16 / ratio,
          bottom: 16 / ratio,
          left: 14 / ratio,
          right: 14 / ratio,
        ),
        child: Row(
          children: [
            Text(
              "方案名称",
              style: TextStyle(color: MyBlack, fontSize: 24 / ratio),
            ),
            SizedBox(width: 290 / ratio),
            Text(
              "社区名称",
              style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
            ),
            SizedBox(width: 210 / ratio),
            Text(
              "方案预算",
              style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
            ),
            SizedBox(width: 79 / ratio),
            Text(
              "渲染金额",
              style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
            ),
            Spacer(), // 添加 Spacer 将 "渲染时间" 推到最右边
            Text(
              "渲染时间",
              style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
            ),
          ],
        ),
      ),
    );
  }
}

class Item extends StatelessWidget {
  void _launchAndroidActivity(String id, String url) {
    platformMethodChannel.invokeMethod('launchActivity', {
      'id': id,
      'url': url,
    });
  }

  final Item147 product;

  const Item({super.key, required this.product});

  @override
  Widget build(BuildContext context) {
    final top =
        product.position == 3
            ? Radius.circular(10 / ratio)
            : product.position == 0
            ? Radius.circular(10 / ratio)
            : Radius.zero;
    final bottom =
        product.position == 3
            ? Radius.circular(10 / ratio)
            : product.position == 2
            ? Radius.circular(10 / ratio)
            : Radius.zero;

    return GestureDetector(
      onTap: () {
        print('on Tap _launchAndroidActivity');
        _launchAndroidActivity(product.id, product.url);
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
            topLeft: top,
            topRight: top,
            bottomLeft: bottom,
            bottomRight: bottom,
          ),
          color: Colors.white.withOpacity(0.40),
          border: Border(
            bottom: BorderSide(
              color: MyBlack.withOpacity(0.20), // bottom边框颜色
              width: 1 / ratio, // 顶部边框宽度
            ),
          ),
        ),
        // color: Colors.red.withAlpha(102),
        child: Padding(
          padding: EdgeInsets.only(
            top: 16 / ratio,
            bottom: 16 / ratio,
            left: 14 / ratio,
            right: 14 / ratio,
          ),
          child: Row(
            children: [
              SizedBox(
                width: 340 / ratio,
                child: Text(
                  product.name,
                  style: TextStyle(color: MyBlack, fontSize: 24 / ratio),
                ),
              ),
              SizedBox(width: 50 / ratio),
              SizedBox(
                width: 280 / ratio,
                child: Text(
                  product.housePlanName,
                  style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
                ),
              ),
              SizedBox(width: 0 / ratio),
              SizedBox(
                width: 128 / ratio,
                child: Text(
                  textAlign: TextAlign.end,
                  formatWithThousandSeparator(product.quoteTotalAmount),
                  style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
                ),
              ),
              SizedBox(width: 54 / ratio),
              SizedBox(
                width: 120 / ratio,
                child: Text(
                  textAlign: TextAlign.end,
                  product.renderTotalAmount.toString(),
                  style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
                ),
              ),
              Spacer(), // 添加 Spacer 将 "渲染时间" 推到最右边
              Text(
                product.date,
                style: TextStyle(fontSize: 24 / ratio, color: MyBlack),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// Formats a number with thousand separators, preserving the decimal part.
/// [number]: The number to format.
/// Returns a string representation with commas for thousand separators.
String formatWithThousandSeparator(double number) {
  final formatter = NumberFormat('#,##0.##'); // Pattern to include decimals
  return formatter.format(number);
}

class Content extends StatelessWidget {
  const Content({super.key});

  @override
  Widget build(BuildContext context) {
    final products = context.watch<CustomerDetailsProvider>().list3;
    return RobotCard(
      child: Padding(
        padding: EdgeInsets.only(left: 30 / ratio, right: 30 / ratio),
        child: SizedBox(
          child: ClipRRect(
            borderRadius: BorderRadius.circular(20.0 / ratio),
            // 保持 CustomScrollView 圆角一致
            child: CustomScrollView(
              physics: BouncingScrollPhysics(),
              slivers: [
                SliverToBoxAdapter(child: Info()),
                SliverToBoxAdapter(child: Title()),
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      if (!products[index].isTitle) {
                        return Item(product: products[index]);
                      } else {
                        return Padding(
                          padding: EdgeInsets.only(
                            left: 12 / ratio,
                            top: 20 / ratio,
                            bottom: 20 / ratio,
                          ),
                          child: Text(
                            products[index].name,
                            style: TextStyle(fontSize: 24 / ratio),
                          ),
                        );
                      }
                    },
                    childCount: products.length, // Number of items
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
